window.addEventListener('load', () => {
  const playIconSVG = '<svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z"></path></svg>'
  const pauseIconSVG =
    '<svg viewBox="0 0 24 24"><path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"></path></svg>'

  const playPauseBtn = document.getElementById('play-pause-btn')
  const audio = document.getElementById('audio')
  const progressBar = document.getElementById('progress-bar')
  const progressContainer = document.getElementById('progress-bar-container')
  const currentTimeEl = document.getElementById('current-time')
  const totalDurationEl = document.getElementById('total-duration')

  let isPlaying = false

  function playSong() {
    isPlaying = true
    playPauseBtn.innerHTML = pauseIconSVG
    audio.play().catch(error => console.error('Audio Playback Error:', error))
  }

  function pauseSong() {
    isPlaying = false
    playPauseBtn.innerHTML = playIconSVG
    audio.pause()
  }

  function formatTime(seconds) {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = Math.floor(seconds % 60)
    return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`
  }

  function updateProgress(e) {
    const {duration, currentTime} = e.srcElement
    if (duration) {
      const progressPercent = (currentTime / duration) * 100
      progressBar.style.width = `${progressPercent}%`
      currentTimeEl.textContent = formatTime(currentTime)
    }
  }

  function setDuration() {
    console.log('Audio Metadata Loaded')
    const duration = audio.duration
    console.log('Audio Duration:', duration)
    if (!isNaN(duration)) {
      totalDurationEl.textContent = formatTime(duration)
    }
  }

  function setProgress(e) {
    const width = this.clientWidth
    const clickX = e.offsetX
    const duration = audio.duration
    if (!isNaN(duration)) {
      audio.currentTime = (clickX / width) * duration
    }
  }

  playPauseBtn.addEventListener('click', () => (isPlaying ? pauseSong() : playSong()))

  audio.addEventListener('timeupdate', updateProgress)
  audio.addEventListener('canplay', setDuration)
  audio.addEventListener('ended', pauseSong)

  progressContainer.addEventListener('click', setProgress)
})
